package demo.applet;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.LinkedList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;

import javax.swing.JApplet;

import netscape.javascript.JSObject;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;

import demo.util.Encoding;

public class KeepVidDownloader extends JApplet {

    private static final String UA_STRING = "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.861.0 Safari/535.2 AppEngine-Google;";

    private String mv_decrypt(String input, int k1, int k2) {
        LinkedList req1 = new LinkedList();
        int req3 = 0;
        while (req3 < input.length()) {
            char c = input.charAt(req3);
            switch (c) {
            case '0':
                req1.add(Integer.valueOf(0));
                req1.add(Integer.valueOf(0));
                req1.add(Integer.valueOf(0));
                req1.add(Integer.valueOf(0));
                break;
            case '1':
                req1.add(Integer.valueOf(0));
                req1.add(Integer.valueOf(0));
                req1.add(Integer.valueOf(0));
                req1.add(Integer.valueOf(1));
                break;
            case '2':
                req1.add(Integer.valueOf(0));
                req1.add(Integer.valueOf(0));
                req1.add(Integer.valueOf(1));
                req1.add(Integer.valueOf(0));
                break;
            case '3':
                req1.add(Integer.valueOf(0));
                req1.add(Integer.valueOf(0));
                req1.add(Integer.valueOf(1));
                req1.add(Integer.valueOf(1));
                break;
            case '4':
                req1.add(Integer.valueOf(0));
                req1.add(Integer.valueOf(1));
                req1.add(Integer.valueOf(0));
                req1.add(Integer.valueOf(0));
                break;
            case '5':
                req1.add(Integer.valueOf(0));
                req1.add(Integer.valueOf(1));
                req1.add(Integer.valueOf(0));
                req1.add(Integer.valueOf(1));
                break;
            case '6':
                req1.add(Integer.valueOf(0));
                req1.add(Integer.valueOf(1));
                req1.add(Integer.valueOf(1));
                req1.add(Integer.valueOf(0));
                break;
            case '7':
                req1.add(Integer.valueOf(0));
                req1.add(Integer.valueOf(1));
                req1.add(Integer.valueOf(1));
                req1.add(Integer.valueOf(1));
                break;
            case '8':
                req1.add(Integer.valueOf(1));
                req1.add(Integer.valueOf(0));
                req1.add(Integer.valueOf(0));
                req1.add(Integer.valueOf(0));
                break;
            case '9':
                req1.add(Integer.valueOf(1));
                req1.add(Integer.valueOf(0));
                req1.add(Integer.valueOf(0));
                req1.add(Integer.valueOf(1));
                break;
            case 'a':
                req1.add(Integer.valueOf(1));
                req1.add(Integer.valueOf(0));
                req1.add(Integer.valueOf(1));
                req1.add(Integer.valueOf(0));
                break;
            case 'b':
                req1.add(Integer.valueOf(1));
                req1.add(Integer.valueOf(0));
                req1.add(Integer.valueOf(1));
                req1.add(Integer.valueOf(1));
                break;
            case 'c':
                req1.add(Integer.valueOf(1));
                req1.add(Integer.valueOf(1));
                req1.add(Integer.valueOf(0));
                req1.add(Integer.valueOf(0));
                break;
            case 'd':
                req1.add(Integer.valueOf(1));
                req1.add(Integer.valueOf(1));
                req1.add(Integer.valueOf(0));
                req1.add(Integer.valueOf(1));
                break;
            case 'e':
                req1.add(Integer.valueOf(1));
                req1.add(Integer.valueOf(1));
                req1.add(Integer.valueOf(1));
                req1.add(Integer.valueOf(0));
                break;
            case 'f':
                req1.add(Integer.valueOf(1));
                req1.add(Integer.valueOf(1));
                req1.add(Integer.valueOf(1));
                req1.add(Integer.valueOf(1));
            case ':':
            case ';':
            case '<':
            case '=':
            case '>':
            case '?':
            case '@':
            case 'A':
            case 'B':
            case 'C':
            case 'D':
            case 'E':
            case 'F':
            case 'G':
            case 'H':
            case 'I':
            case 'J':
            case 'K':
            case 'L':
            case 'M':
            case 'N':
            case 'O':
            case 'P':
            case 'Q':
            case 'R':
            case 'S':
            case 'T':
            case 'U':
            case 'V':
            case 'W':
            case 'X':
            case 'Y':
            case 'Z':
            case '[':
            case '\\':
            case ']':
            case '^':
            case '_':
            case '`':
            }
            req3++;
        }

        LinkedList req6 = new LinkedList();
        req3 = 0;
        while (req3 < 384) {
            k1 = (k1 * 11 + 77213) % 81371;
            k2 = (k2 * 17 + 92717) % 192811;
            req6.add(Integer.valueOf((k1 + k2) % 128));
            req3++;
        }
        req3 = 256;
        while (req3 >= 0) {
            int req5 = ((Integer) req6.get(req3)).intValue();
            int req4 = req3 % 128;
            int req8 = ((Integer) req1.get(req5)).intValue();
            req1.set(req5, req1.get(req4));
            req1.set(req4, Integer.valueOf(req8));
            req3--;
        }
        req3 = 0;
        while (req3 < 128) {
            req1.set(
                    req3,
                    Integer.valueOf(((Integer) req1.get(req3)).intValue() ^ ((Integer) req6.get(req3 + 256)).intValue()
                            & 0x1));
            req3++;
        }

        String out = "";
        req3 = 0;
        while (req3 < req1.size()) {
            int tmp = ((Integer) req1.get(req3)).intValue() * 8;
            tmp += ((Integer) req1.get(req3 + 1)).intValue() * 4;
            tmp += ((Integer) req1.get(req3 + 2)).intValue() * 2;
            tmp += ((Integer) req1.get(req3 + 3)).intValue();
            switch (tmp) {
            case 0:
                out = out + "0";
                break;
            case 1:
                out = out + "1";
                break;
            case 2:
                out = out + "2";
                break;
            case 3:
                out = out + "3";
                break;
            case 4:
                out = out + "4";
                break;
            case 5:
                out = out + "5";
                break;
            case 6:
                out = out + "6";
                break;
            case 7:
                out = out + "7";
                break;
            case 8:
                out = out + "8";
                break;
            case 9:
                out = out + "9";
                break;
            case 10:
                out = out + "a";
                break;
            case 11:
                out = out + "b";
                break;
            case 12:
                out = out + "c";
                break;
            case 13:
                out = out + "d";
                break;
            case 14:
                out = out + "e";
                break;
            case 15:
                out = out + "f";
            }

            req3 += 4;
        }
        return out;
    }

    private String inbtwn(String a, String b, String c) {
        try {
            String[] arr1 = a.split(b);
            try {
                String[] arr2 = arr1[1].split(c);
                if ((arr2[0] != null) || (arr2[0] != ""))
                    return arr2[0];
            } catch (Exception ex) {
                return arr1[1];
            }
            return arr1[1];
        } catch (Exception ex) {
        }
        return null;
    }

    private String inbtwnmore(String input, String startcut, String finishcut, int times) {
        String output = null;
        try {
            String[] arr1 = input.split(startcut);
            String[] arr2 = arr1[times].split(finishcut);
            output = arr2[0];
        } catch (Exception ex) {
            return null;
        }
        return output;
    }

    private String pregMatch(String regexp, String haystack, int mat) {
        try {
            Matcher matcher = Pattern.compile(regexp).matcher(haystack);
            return matcher.group(mat);
        } catch (Exception ex) {
            System.out.println(ex);
        }
        return null;
    }

    @Override
    public String getParameter(String name) {
        // TODO Auto-generated method stub
        return super.getParameter(name);
    }

    @Override
    public void init() {
        if (!getDocumentBase().getHost().toLowerCase().contains("keepvid.com")) {
            throw new SecurityException("java.io.* import failed.");
        }

        JSObject mainWindow = JSObject.getWindow(this);
        mainWindow.eval("jloaded();");
        String error = null;

        try {
            super.init();
            String uParam = getParameter("u");

            System.out.println("param u: " + uParam + "\r\n");

            if ((uParam.contains("youtube.com")) || (uParam.contains("youtu.be"))) {
                try {
                    if (uParam.contains("youtu.be/")) {
                        uParam = uParam.replace("youtu.be/", "www.youtube.com/watch?v=").toString();
                    }

                    String pageSource = getUrlContent(uParam + "&fmt=18", "GET", "");
                    String video_id = inbtwn(pageSource, "shortlink\" href=\"http://youtu.be/", "\"");
                    if (video_id == null) {
                        video_id = inbtwn(pageSource, "'VIDEO_ID': \"", "\"");
                    }
                    if (video_id == null) {
                        System.out.println("Trying Alternate Method...");
                        video_id = inbtwn(uParam, "v=", "&");
                        pageSource = getUrlContent("http://www.youtube.com/get_video_info?video_id=" + video_id
                                + "&asv=3&el=detailpage&hl=en_US", "GET", "");
                    }

                    System.out.println("Getting Title...");
                    String title = inbtwn(pageSource, "'VIDEO_TITLE': '", "',");
                    if (title == null)
                        title = inbtwn(pageSource, "name=\"title\" content=\"", "\"");
                    if (title == null)
                        title = URLDecoder.decode(inbtwn(pageSource, "&title=", "&"), "UTF-8").replace("+", " ");
                    try {
                        title = setHTMLEntity(title);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                    System.out.println("Title: " + title + "\r\n");

                    mainWindow.eval("kv_info('" + title + "', 'youtube.com', 'http://www.youtube.com/watch?v="
                            + video_id + "', 'http://i.ytimg.com/vi/" + video_id + "/default.jpg');");

                    String fmt_url_map = "";
                    fmt_url_map = URLDecoder.decode(inbtwn(pageSource, "fmt_stream_map=", "&"), "UTF-8");
                    if (fmt_url_map == null)
                        fmt_url_map = inbtwn(pageSource, "fmt_stream_map\": \"", "\"").replace("\\/", "/");
                    System.out.println("fmt_url_map: " + fmt_url_map + "\r\n");

                    String dl_3gplow = null;
                    String dl_3gpmed = null;
                    String dl_3gphigh = null;
                    String dl_flvlow = null;
                    String dl_flvmed = null;
                    String dl_flvmed2 = null;
                    String dl_flvhigh = null;
                    String dl_mp4high = null;
                    String dl_mp4hd = null;
                    String dl_mp4hd2 = null;
                    String dl_mp4hd3 = null;
                    String dl_webm = null;
                    String dl_webmhd = null;
                    String dl_webmhd2 = null;

                    String[] fmt_arr = fmt_url_map.split("url=");
                    for (String fmt : fmt_arr) {
                        String[] parts = fmt.split(Pattern.quote("&qual"));
                        String m_url = URLDecoder.decode(parts[0], "UTF-8");
                        if (m_url.contains("itag=13"))
                            dl_3gplow = m_url;
                        if (m_url.contains("itag=17"))
                            dl_3gpmed = m_url;
                        if (m_url.contains("itag=36"))
                            dl_3gphigh = m_url;
                        if (m_url.contains("itag=5"))
                            dl_flvlow = m_url;
                        if (m_url.contains("itag=34"))
                            dl_flvmed = m_url;
                        if (m_url.contains("itag=6"))
                            dl_flvmed2 = m_url;
                        if (m_url.contains("itag=35"))
                            dl_flvhigh = m_url;
                        if (m_url.contains("itag=18"))
                            dl_mp4high = m_url;
                        if (m_url.contains("itag=22"))
                            dl_mp4hd = m_url;
                        if (m_url.contains("itag=37"))
                            dl_mp4hd2 = m_url;
                        if (m_url.contains("itag=38"))
                            dl_mp4hd3 = m_url;
                        if (m_url.contains("itag=43"))
                            dl_webm = m_url;
                        if (m_url.contains("itag=44"))
                            dl_webmhd = m_url;
                        if (m_url.contains("itag=45"))
                            dl_webmhd2 = m_url;
                        System.out.println("URL: " + m_url);
                    }

                    if (error == null) {
                        if (dl_flvlow != null)
                            mainWindow.eval("kv_ds('dl_flvlow', 'FLV', '240p', '" + dl_flvlow + "', '" + title + "');");
                        if (dl_flvmed2 != null)
                            mainWindow.eval("kv_ds('dl_flvmed2', 'FLV', '360p', '" + dl_flvmed2 + "', '" + title
                                    + "');");
                        if (dl_flvmed != null)
                            mainWindow.eval("kv_ds('dl_flvmed', 'FLV', '360p', '" + dl_flvmed + "', '" + title + "');");
                        if (dl_flvhigh != null)
                            mainWindow.eval("kv_ds('dl_flvhigh', 'FLV', '480p', '" + dl_flvhigh + "', '" + title
                                    + "');");
                        if (dl_mp4high != null)
                            mainWindow.eval("kv_ds('dl_mp4high', 'MP4', '(Max 480p)', '" + dl_mp4high + "', '" + title
                                    + "');");
                        if (dl_mp4hd != null)
                            mainWindow.eval("kv_ds('dl_mp4hd', 'MP4', '720p', '" + dl_mp4hd + "', '" + title + "');");
                        if (dl_mp4hd2 != null)
                            mainWindow
                                    .eval("kv_ds('dl_mp4hd2', 'MP4', '1080p', '" + dl_mp4hd2 + "', '" + title + "');");
                        if (dl_mp4hd3 != null)
                            mainWindow.eval("kv_ds('dl_mp4hd3', 'MP4', '(Original)', '" + dl_mp4hd3 + "', '" + title
                                    + "');");
                        if (dl_webm != null)
                            mainWindow.eval("kv_ds('dl_webm', 'WebM', '360p', '" + dl_webm + "', '" + title + "');");
                        if (dl_webmhd != null)
                            mainWindow
                                    .eval("kv_ds('dl_webmhd', 'WebM', '480p', '" + dl_webmhd + "', '" + title + "');");
                        if (dl_webmhd2 != null)
                            mainWindow.eval("kv_ds('dl_webmhd2', 'WebM', '720p', '" + dl_webmhd2 + "', '" + title
                                    + "');");
                        try {
                            String pageMob = getUrlContent("http://m.youtube.com/watch?ajax=1&layout=mobile&tsp=1&v="
                                    + video_id, "GET", "");
                            String[] splmini = pageMob.split("\"related_videos\":");
                            pageMob = splmini[0];
                            dl_3gphigh = inbtwn(pageMob, "\"stream_url\": \"", "\"").replace("\\/", "/");
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                        if (dl_3gplow != null)
                            mainWindow.eval("kv_ds('dl_3gplow', '3GP', '144p', '" + dl_3gplow + "', '" + title + "');");
                        if (dl_3gpmed != null)
                            mainWindow.eval("kv_ds('dl_3gpmed', '3GP', '144p', '" + dl_3gpmed + "', '" + title + "');");
                        if (dl_3gphigh != null)
                            mainWindow.eval("kv_ds('dl_3gphigh', '3GP', '240p', '" + dl_3gphigh + "', '" + title
                                    + "');");
                    } else {
                        mainWindow.eval("kv_error('" + error + "');");
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            } else if (uParam.contains("megavideo.com")) {
                try {
                    String pageSource = getUrlContent(uParam, "GET", "");
                    String video_id = inbtwn(pageSource, "flashvars.v = \"", "\"");
                    String un = inbtwn(pageSource, "flashvars.un = \"", "\"");
                    int k1 = Integer.valueOf(inbtwn(pageSource, "flashvars.k1 = \"", "\"")).intValue();
                    int k2 = Integer.valueOf(inbtwn(pageSource, "flashvars.k2 = \"", "\"")).intValue();
                    String s = inbtwn(pageSource, "flashvars.s = \"", "\"");
                    String title = inbtwn(pageSource, "flashvars.title = \"", "\"");
                    title = URLDecoder.decode(setHTMLEntity(title).replace("+", " "), "UTF-8");
                    String imgsrc = inbtwn(pageSource, "flashvars.image = \"", "\"");
                    mainWindow.eval("kv_info('" + title + "', 'megavideo.com', 'http://www.megavideo.com/?v="
                            + video_id + "', '" + imgsrc + "');");

                    String hashresult = mv_decrypt(un, k1, k2);
                    String mv_flv = "http://www" + s + ".megavideo.com/files/" + hashresult + "/" + title
                            + " [www.keepvid.com].flv";
                    String hd_url = null;
                    try {
                        hd_url = URLDecoder.decode(inbtwn(pageSource, "hd_url=\"", "\""), "UTF-8");
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                    if (hd_url != null)
                        hd_url = hd_url + title + " [www.keepvid.com].mp4";
                    if (mv_flv != null)
                        mainWindow.eval("kv_ds('mv_flv', 'FLV', 'High Quality - 480x270', '" + mv_flv + "', '" + title
                                + "');");
                    if (hd_url != null)
                        mainWindow.eval("kv_ds('mv_mp4', 'MP4', 'High Definition - 1280x720', '" + hd_url + "', '"
                                + title + "');");
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            } else if (uParam.contains("dailymotion.com")) {
                try {
                    String pageSource = getUrlContent(uParam, "GET", "");
                    String sequence = URLDecoder.decode(inbtwn(pageSource, "\"sequence\",  \"", "\""), "UTF-8")
                            .replace("\\/", "/");
                    String title = inbtwn(pageSource, "DMTITLE=", "&");

                    String imgsrc = inbtwn(pageSource, "og:image\" content=\"", "\"");
                    if (imgsrc == null)
                        imgsrc = inbtwn(pageSource, "/jpeg\" href=\"", "\"");
                    mainWindow.eval("kv_info('" + title + "', 'dailymotion.com', '" + uParam + "', '" + imgsrc + "');");

                    String dm_low = inbtwn(sequence, "\"sdURL\":\"", "\"");
                    String dm_high = inbtwn(sequence, "\"hqURL\":\"", "\"");

                    if ((dm_low != null) && (dm_low.contains("flv")))
                        mainWindow.eval("kv_ds('dm_low', 'FLV', 'Standard Quality', '" + getRedirUrl(dm_low)
                                + "', '');");
                    if ((dm_low != null) && (dm_low.contains("mp4")))
                        mainWindow.eval("kv_ds('dm_low', 'MP4', 'Standard Quality', '" + getRedirUrl(dm_low)
                                + "', '');");
                    if ((dm_high != null) && (dm_high.contains("flv")))
                        mainWindow.eval("kv_ds('dm_high', 'FLV', 'High Quality', '" + getRedirUrl(dm_high) + "', '');");
                    if ((dm_high != null) && (dm_high.contains("mp4")))
                        mainWindow.eval("kv_ds('dm_high', 'MP4', 'High Quality', '" + getRedirUrl(dm_high) + "', '');");
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            } else if (uParam.contains("twitvid.com")) {
                try {
                    String pageSource = getUrlContent(uParam, "GET", "");
                    String title = inbtwn(pageSource, "title\" content=\"", "\"");

                    String imgsrc = inbtwn(pageSource, "image\" content=\"", "\"");
                    mainWindow.eval("kv_info('" + title + "', 'twitvid.com', '" + uParam + "', '" + imgsrc + "');");

                    String tv_mp4 = URLDecoder.decode(inbtwn(pageSource, "file=", "&"), "UTF-8");
                    if (tv_mp4 != null)
                        mainWindow.eval("kv_ds('tv_mp4', 'MP4', 'Standard Quality', '" + tv_mp4 + "', '');");
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            } else if (uParam.contains("tudou.com")) {
                try {
                    String firstSource = getUrlContent(uParam, "GET", "");
                    String iid = inbtwn(firstSource, "defaultIid = ", "\n");
                    if (iid == null)
                        iid = inbtwn(firstSource, "iid = ", "\n");
                    if (iid == null)
                        iid = inbtwn(uParam, "iid=", "&");
                    if (iid == null)
                        iid = inbtwn(firstSource, "iid:", "\n");

                    String title = inbtwn(firstSource, "kw = title = \"", "\"");
                    String imgsrc = inbtwn(firstSource, "thumbnail = pic = '", "'");
                    mainWindow.eval("kv_info('" + title + "', 'tudou.com', '" + uParam + "', '" + imgsrc + "');");

                    String maincons = null;
                    if (uParam.contains("hd."))
                        maincons = "http://v2.tudou.com/v2/kili?id=";
                    else
                        maincons = "http://v2.tudou.com/v?it=";
                    String pageSource = getUrlContent(maincons + iid, "GET", "");

                    String[] file_arr = pageSource.split("<f ");
                    for (String file_a : file_arr)
                        if (file_a.contains("size=\"")) {
                            String[] arr1 = file_a.split(">");
                            String[] arr2 = arr1[1].split("</");
                            String file = arr2[0];
                            System.out.println(file);
                            if (file.contains("h264_3")) {
                                mainWindow.eval("kv_ds('td_flv3', 'FLV', '480p', '" + file + "', '');");
                            } else if (file.contains("h264_2")) {
                                mainWindow.eval("kv_ds('td_flv2', 'FLV', '360p', '" + file + "', '');");
                            } else if (file.contains("h264_1")) {
                                mainWindow.eval("kv_ds('td_flv1', 'FLV', '256p', '" + file + "', '');");
                            } else {
                                if (!file.contains(".flv"))
                                    continue;
                                mainWindow.eval("kv_ds('td_flv', 'FLV', 'Standard Quality', '" + file + "', '');");
                            }
                        }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            } else if (uParam.contains("videoweed.es")) {
                try {
                    String pageSource = getUrlContent(uParam, "GET", "");
                    String title = inbtwn(pageSource, "title\" content=\"", "\"");
                    String imgsrc = inbtwn(pageSource, "image_src\" href=\"", "\"");
                    mainWindow.eval("kv_info('" + title + "', 'videoweed.es', '" + uParam + "', '" + imgsrc + "');");

                    String file = inbtwn(pageSource, ".file=\"", "\"");
                    String filekey = inbtwn(pageSource, ".filekey=\"", "\"");
                    String fileSource = getUrlContent(
                            "http://www.videoweed.es/api/player.api.php?user=undefined&codes=undefined&pass=undefined&file="
                                    + file + "&key=" + filekey, "GET", "");

                    String flv = inbtwn(fileSource, "url=", "&");
                    mainWindow.eval("kv_ds('vw_flv', 'FLV', 'Standard Quality', '" + flv + "', '');");
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            } else if (uParam.contains("stagevu.com")) {
                try {
                    String pageSource = getUrlContent(uParam, "GET", "");
                    String title = inbtwn(pageSource, "name=\"movieTitle\" value=\"", "\"");

                    String imgsrc = inbtwn(pageSource, "name=\"previewImage\" value=\"", "\"");
                    mainWindow.eval("kv_info('" + title + "', 'stagevu.com', '" + uParam + "', '" + imgsrc + "');");

                    String file = inbtwn(pageSource, "name=\"src\" value=\"", "\"");
                    mainWindow.eval("kv_ds('sv_flv', 'AVI', 'High Quality', '" + file + "', '');");
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            } else if (uParam.contains("vbox7.com")) {
                try {
                    String video_id = inbtwn(uParam, "play:", "?");
                    String xmlSource = getUrlContent("http://vbox7.com/etc/ext.do?key=" + video_id, "GET", "");
                    String imgsrc = inbtwn(xmlSource, "jpg_addr=", "&");
                    if (imgsrc != null)
                        imgsrc = "http://" + imgsrc;
                    mainWindow.eval("kv_info('', 'vbox7.com', '" + uParam + "', '" + imgsrc + "');");

                    System.out.println(video_id);
                    String file = inbtwn(xmlSource, "flv_addr=", "&");
                    if (file != null)
                        file = "http://" + file;
                    mainWindow.eval("kv_ds('vb_flv', 'FLV', 'High Quality', '" + file + "', '');");
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            } else if (uParam.contains("zshare.net")) {
                try {
                    String pageSource = getUrlContent(uParam, "GET", "");
                    String pageSource2 = getUrlContent(
                            "http://www.zshare.net/videoplayer"
                                    + inbtwn(pageSource, "/videoplayer", "\"").replace(" ", "%20"), "GET", "");
                    String title = inbtwn(pageSource, "<h2>Watching ", "<");
                    mainWindow.eval("kv_info('" + title + "', 'zshare.net', '" + uParam
                            + "', 'http://www.zshare.net/images/logoSmall.png');");

                    String flv = inbtwn(pageSource2, "file: \"", "\"");
                    if (flv != "")
                        mainWindow.eval("kv_ds('zs_flv', 'FLV', 'High Quality', '" + flv + "', '');");
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            } else if (uParam.contains("v.9you.com")) {
                try {
                    String pageSource = getUrlContent(uParam, "GET", "");
                    String pageSource2 = getUrlContent(
                            "http://v.9you.com/source.jsp?id=" + inbtwn(uParam, "watch/", ".html"), "GET", "");
                    String title = inbtwn(pageSource, "<title>", " -");
                    String imgsrc = URLDecoder.decode(inbtwn(pageSource2, "image=\"", "\""), "UTF-8");
                    mainWindow.eval("kv_info('" + title + "', 'v.9you.com', '" + uParam + "', '" + imgsrc + "');");

                    String flv = URLDecoder.decode(inbtwn(pageSource2, "flv=\"", "\""), "UTF-8");
                    if (flv != "")
                        mainWindow.eval("kv_ds('y9_flv', 'FLV', 'High Quality', '" + flv + "', '');");
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            } else if (uParam.contains("altervideo.net")) {
                try {
                    String pageSource = getUrlContent(uParam, "GET", "");
                    String c = inbtwn(pageSource, " type=\"hidden\" value=\"", "\"");
                    String pageSource2 = postUrlContent(uParam, "c=" + c + "&choice=Watch Online", "c=" + c);

                    String[] fer = null;
                    if (pageSource.contains("addVariable"))
                        fer = inbtwn(pageSource, "addParam", "'").split("\\|");
                    if (pageSource2.contains("addVariable"))
                        fer = inbtwn(pageSource2, "addParam", "'").split("\\|");

                    String flv = "http://" + fer[31] + ".altervideo.net/files/" + fer[33] + "/" + fer[30]
                            + "/altervideo/" + fer[22] + ".flv?start=0";
                    if (flv != "")
                        mainWindow.eval("kv_ds('av_flv', 'FLV', 'High Quality', '" + flv + "', '');");
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            } else if (uParam.contains("clip.vn")) {
                try {
                    String v = inbtwn(uParam, ",", "?");
                    String pa = getUrlContent("http://clip.vn/movies/nfo/" + v, "GET", "");
                    String title = setHTMLEntity(inbtwn(pa, "<title><!\\[CDATA\\[", "\\]\\]"));
                    String imgsrc = inbtwn(pa, "thumbnail url=\"", "\"");
                    mainWindow.eval("kv_info('" + title + "', 'clip.vn', '" + uParam + "', '" + imgsrc + "');");

                    String[] arr = pa.split("enclosure url=");
                    for (String file_a : arr)
                        if (file_a.contains(".mp4")) {
                            String file = inbtwn(file_a, "'", "'");
                            System.out.println(file);
                            String res = inbtwn(file_a, "quality='", "'");
                            if (res.equals("1"))
                                mainWindow.eval("kv_ds('cv_mp41', 'MP4', '240p', '" + file + "', '');");
                            if (res.equals("2"))
                                mainWindow.eval("kv_ds('cv_mp42', 'MP4', '360p', '" + file + "', '');");
                            if (!res.equals("3"))
                                continue;
                            mainWindow.eval("kv_ds('cv_mp43', 'MP4', '480p', '" + file + "', '');");
                        }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            } else if (uParam.contains("divxstage.eu")) {
                try {
                    String pa = getUrlContent(uParam, "GET", "");
                    String t = setHTMLEntity(inbtwn(pa, "<title>", " - DivxStage</"));
                    String i = inbtwn(pa, "image_src\" href=\"", "\"");
                    mainWindow.eval("kv_info('" + t + "', 'divxstage.eu', '" + uParam + "', '" + i + "');");
                    String f = inbtwn(pa, "video/divx\" src=\"", "\"");
                    if (f != "")
                        mainWindow.eval("kv_ds('ds_avi', 'AVI', 'High Quality', '" + f + "', '');");
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            } else {
                mainWindow.eval("kv_error('Sorry, could not fetch download links on this page (site not supported).')");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * String pageSource = getUrlContent(uParam + "&fmt=18", "GET", "");
     * 
     * @param url
     *            - http://www.youtube.com/watch?v=5YXVMCHG-Nk
     * @param method
     *            - GET
     * @param enc
     * @return
     */
    private String getUrlContent(String url, String method, String enc) {
        String responseBody = null;

        try {
            final URL u = new URL(url);
            final HttpURLConnection conn = (HttpURLConnection) u.openConnection();
            conn.setRequestMethod(method);

            // set request property
            if (url.contains("layout=mobile")) {
                conn.setRequestProperty(
                        "User-Agent",
                        "Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit/528.18 (KHTML, like Gecko) Version/4.0 Mobile/7A341 Safari/528.16");
            } else {
                conn.setRequestProperty("User-Agent", UA_STRING);
            }

            if (url.contains("dailymotion.com")) {
                conn.setRequestProperty("Cookie", "family_filter=off;");
            }

            // input stream
            InputStream in;
            if (url.contains("www.tudou.com")) {
                in = new GZIPInputStream(conn.getInputStream());
            } else {
                in = conn.getInputStream();
            }

            // input -> output
            try {
                final String encoding = StringUtils.defaultIfBlank(enc, Encoding.UTF8);
                responseBody = IOUtils.toString(in, encoding);
            } finally {
                conn.disconnect();
            }

        } catch (Exception e) {
            e.printStackTrace();
            try {
                getAppletContext().showDocument(new URL("javascript:jerror();"));
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

        return responseBody;
    }

    private String postUrlContent(String url, String params, String ck) {
        HttpURLConnection conn = null;
        try {
            URL u = new URL(url);
            conn = (HttpURLConnection) u.openConnection();
            if (ck != null)
                conn.setRequestProperty("Cookie", ck);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Content-Length", "" + Integer.toString(params.getBytes().length));
            conn.setUseCaches(false);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
            wr.writeBytes(params);
            wr.flush();
            wr.close();
            InputStream in = conn.getInputStream();
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            for (int bytesRead = 0; (bytesRead = in.read(buffer)) != -1;)
                output.write(buffer, 0, bytesRead);
            conn.disconnect();
            return output.toString();
        } catch (Exception e) {
            e.printStackTrace();
            try {
                getAppletContext().showDocument(new URL("javascript:jerror();"));
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return null;
    }

    private String getRedirUrl(String url) {
        String hdr = "";
        try {
            HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
            conn.setInstanceFollowRedirects(false);
            conn.addRequestProperty("User-Agent", getParameter("ua"));
            hdr = conn.getHeaderField("location");
        } catch (Exception e) {
            e.printStackTrace();
            try {
                getAppletContext().showDocument(new URL("javascript:jerror();"));
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            return null;
        }
        return hdr;
    }

    private String setHTMLEntity(String input) {
        String output = "";
        try {
            output = input.replace("&amp;", "").toString().replace("&lt;", "").toString().replace("&gt;", "")
                    .toString().replace("&#39;", "").toString().replace("&quot;", "").toString().replace("&", "")
                    .toString().replace("amp;", "").toString().replace("\\\"", "").toString().replace("\\'", "")
                    .toString().replace("'", "").toString().replace("'", "").toString().replace("<", "").toString()
                    .replace(">", "").toString().replace("?", "").toString().replace("/", "").toString()
                    .replace(":", "").toString().replace(";", "").toString().replace("#", "").toString();
        } catch (Exception e) {
            e.printStackTrace();
            return input;
        }
        return output;
    }
}